<template>
  <div>

    <div class="d-flex align-center justify-space-between mb-3">
      <div class="text-h6 font-weight-bold brand-logo">Role Management</div>
      <div class="d-flex align-center">
        <v-text-field
          v-model.trim="queryInput"
          class="mr-2"
          style="width: 280px;"
          outlined
          dense
          clearable
          hide-details
          label="Search (e.g. name:admin code:R01)"
          append-icon="mdi-magnify"
          @keyup.enter="onSearchFromInput"
          @click:append="onSearchFromInput"
          @click:clear="onResetInput"
        />
        <v-btn class="mr-2" outlined>Export</v-btn>
        <v-btn color="primary" dark @click="openAddDialog">+ Add Role</v-btn>
      </div>
    </div>

    <v-data-table
      :headers="headers"
      :items="roles"
      :items-per-page="pageSize"
      :page.sync="pageNum"
      :server-items-length="total"
      :loading="loading"
      class="elevation-1"
      dense
      @update:page="onPageChange"
      @update:items-per-page="onPageSizeChange"
      @click:row="onRowClick"
    >
      <template v-slot:item.isActive="{ item }">
        <v-chip small :color="item.isActive ? 'green lighten-4' : 'red lighten-4'" :text-color="item.isActive ? 'green darken-2' : 'red darken-2'">
          {{ item.isActive ? 'Active' : 'Inactive' }}
        </v-chip>
      </template>
      <template v-slot:item.actions>
        <v-btn x-small outlined color="primary" class="mr-1" @click="openEditDialog(item)">Edit</v-btn>
        <v-btn x-small outlined color="error" @click="confirmDelete(item)">Delete</v-btn>
      </template>
    </v-data-table>

    <!-- Add/Edit Role Dialog -->
    <v-dialog v-model="dialog" max-width="520px">
      <v-card>
        <v-card-title class="font-weight-bold">{{ isEdit ? 'Edit Role' : 'Add Role' }}</v-card-title>
        <v-divider></v-divider>
        <v-card-text>
          <v-form ref="form" v-model="formValid">
            <v-text-field v-model="formModel.roleCode" label="Code" outlined dense :rules="[rules.required]" />
            <v-text-field v-model="formModel.name" label="Name" outlined dense :rules="[rules.required]" />
            <v-text-field v-model="formModel.description" label="Description" outlined dense :rules="[rules.required]" />
            <div class="d-flex align-center mt-2">
              <v-switch v-model="formModel.isActive" inset label="Active" class="ma-0" />
            </div>
          </v-form>
        </v-card-text>
        <v-divider></v-divider>
        <v-card-actions class="justify-end">
          <v-btn text @click="closeDialog">Cancel</v-btn>
          <v-btn color="primary" dark @click="submitRole">Save</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <!-- Detail Dialog -->
    <v-dialog v-model="detailDialog" max-width="720px">
      <v-card>
        <v-card-title class="font-weight-bold">Role Detail</v-card-title>
        <v-divider></v-divider>
        <v-card-text>
          <v-skeleton-loader v-if="detailLoading" type="article" />
          <div v-else>
            <div class="mb-3">
              <div><strong>ID:</strong> {{ detailRole.id }}</div>
              <div><strong>Code:</strong> {{ detailRole.roleCode }}</div>
              <div><strong>Name:</strong> {{ detailRole.name }}</div>
              <div><strong>Description:</strong> {{ detailRole.description }}</div>
              <div><strong>Status:</strong> {{ detailRole.isActive ? 'Active' : 'Inactive' }}</div>
            </div>
            <div>
              <div class="subtitle-2 font-weight-bold mb-2">Users in this role</div>
              <v-data-table :headers="detailUserHeaders" :items="detailUsers" dense :items-per-page="5">
                <template v-slot:item.id="{ item }">#{{ item.id }}</template>
              </v-data-table>
            </div>
          </div>
        </v-card-text>
        <v-divider></v-divider>
        <v-card-actions class="justify-end">
          <v-btn text @click="detailDialog=false">Close</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </div>
</template>

<script>
export default {
  name: 'RolePage',
  data() {
    return {
      headers: [
        { text: 'ID', value: 'id' },
        { text: 'CODE', value: 'roleCode' },
        { text: 'NAME', value: 'name' },
        { text: 'DESCRIPTION', value: 'description' },
        { text: 'STATUS', value: 'isActive' },
        { text: 'ACTIONS', value: 'actions', sortable: false }
      ],
      roles: [],
      total: 0,
      pageNum: 1,
      pageSize: 10,
      loading: false,
      queryInput: '',
      query: { name: '', roleCode: '', isActive: '' },
      statusOptions: [
        { text: 'Active', value: true },
        { text: 'Inactive', value: false }
      ],
      dialog: false,
      isEdit: false,
      formValid: false,
      formModel: { id: '', roleCode: '', name: '', description: '', isActive: true },
      detailDialog: false,
      detailLoading: false,
      detailRole: {},
      detailUsers: [],
      detailUserHeaders: [
        { text: 'USER ID', value: 'id' },
        { text: 'USERNAME', value: 'username' },
        { text: 'EMAIL', value: 'email' }
      ],
      rules: { required: v => !!(v && String(v).trim()) || 'Required' }
    }
  },
  created() {
    this.fetchRoles()
  },
  methods: {
    async fetchRoles() {
      this.loading = true
      try {
        const q = { ...this.query }
        Object.keys(q).forEach(k => { if (q[k] === '' || q[k] === null || typeof q[k] === 'undefined') delete q[k] })
        const res = await this.$api.role.getRoles({ pageNum: this.pageNum, pageSize: this.pageSize, ...q })
        const payload = res && (res.data || res)
        this.roles = payload.list || payload.items || []
        this.total = Number(payload.total || payload.totalCount || 0)
      } catch (e) {
        // eslint-disable-next-line no-console
        console.error('Failed to fetch roles', e)
      } finally {
        this.loading = false
      }
    },
    onSearch() { this.pageNum = 1; this.fetchRoles() },
    onReset() { this.query = { name: '', roleCode: '', isActive: '' }; this.pageNum = 1; this.fetchRoles() },
    onSearchFromInput() {
      const params = this.parseQueryInput(this.queryInput)
      this.query = { name: '', roleCode: '', isActive: '', ...params }
      this.pageNum = 1
      this.fetchRoles()
    },
    onResetInput() {
      this.queryInput = ''
      this.onReset()
    },
    parseQueryInput(input) {
      const params = {}
      if (!input || !input.trim()) return params
      const tokens = input.trim().split(/\s+/)
      tokens.forEach(t => {
        const idx = t.indexOf(':')
        if (idx > 0) {
          const key = t.slice(0, idx).toLowerCase()
          const valRaw = t.slice(idx + 1)
          const val = valRaw === 'true' ? true : valRaw === 'false' ? false : valRaw
          if (['name'].includes(key)) params.name = val
          else if (['code','role','rolecode'].includes(key)) params.roleCode = val
          else if (['active','status','isactive'].includes(key)) params.isActive = val
        } else {
          // Bare keyword used for both name and roleCode to enhance recall
          if (!params.name && !params.roleCode) {
            params.name = t
            params.roleCode = t
          } else if (!params.name) {
            params.name = t
          } else if (!params.roleCode) {
            params.roleCode = t
          }
        }
      })
      return params
    },
    async confirmDelete(item) {
      if (!item || !item.id) return
      const ok = window.confirm(`Delete role "${item.name}"?`)
      if (!ok) return
      try {
        await this.$api.role.deleteRole(item.id)
        this.fetchRoles()
      } catch (e) {
        // eslint-disable-next-line no-console
        console.error('Failed to delete role', e)
      }
    },
    onPageChange(p) { this.pageNum = p; this.fetchRoles() },
    onPageSizeChange(size) { this.pageSize = size; this.pageNum = 1; this.fetchRoles() },
    openAddDialog() {
      this.isEdit = false
      this.formModel = { id: '', roleCode: '', name: '', description: '', isActive: true }
      this.dialog = true
    },
    openEditDialog(item) {
      this.isEdit = true
      this.formModel = { id: item.id, roleCode: item.roleCode, name: item.name, description: item.description, isActive: !!item.isActive }
      this.dialog = true
    },
    closeDialog() {
      this.dialog = false
      this.$nextTick(() => { if (this.$refs.form) this.$refs.form.resetValidation() })
    },
    async submitRole() {
      if (!this.$refs.form || !this.$refs.form.validate()) return
      try {
        if (this.isEdit) {
          await this.$api.role.updateRole(this.formModel.id, {
            roleCode: this.formModel.roleCode,
            name: this.formModel.name,
            description: this.formModel.description,
            isActive: !!this.formModel.isActive
          })
        } else {
          await this.$api.role.createRole({
            roleCode: this.formModel.roleCode,
            name: this.formModel.name,
            description: this.formModel.description,
            isActive: !!this.formModel.isActive
          })
        }
        this.closeDialog()
        this.fetchRoles()
      } catch (e) {
        // eslint-disable-next-line no-console
        console.error('Failed to submit role', e)
      }
    },
    onRowClick(item, event) {
      if (event && event.detail >= 2) {
        this.openDetail(item)
      }
    },
    async openDetail(item) {
      this.detailDialog = true
      this.detailLoading = true
      this.detailRole = {}
      this.detailUsers = []
      try {
        const roleDetail = await this.$api.role.getRoleById(item.id)
        this.detailRole = (roleDetail && (roleDetail.data || roleDetail)) || item
        const usersFromDetail = this.detailRole.users || this.detailRole.members || []
        if (usersFromDetail && usersFromDetail.length) {
          this.detailUsers = usersFromDetail
        } else {
          const res = await this.$api.user.getUsers({ pageNum: 1, pageSize: 1000, roleCode: this.detailRole.roleCode })
          const payload = res && (res.data || res)
          this.detailUsers = payload.list || payload.items || []
        }
      } catch (e) {
        // eslint-disable-next-line no-console
        console.error('Failed to load role detail', e)
      } finally {
        this.detailLoading = false
      }
    }
  }
}
</script>

<style scoped>
</style>


